<!-- 表单弹窗 -->
<form lay-filter="purQualityTaskAddForm" id="purQualityTaskAddForm" class="layui-form open-form purQualityTaskAddForm">
  <div class="open-model">
    <div class="open-auto">
      <div class="layui-form-item">
        <table class="layui-table" id="myPurQualityTaskFormTable" lay-filter="myPurQualityTaskFormTable"></table>
      </div>
      <div class="layui-form-item">
        <table class="layui-table" id="myPurQualityTaskDetailTable" lay-filter="myPurQualityTaskDetailTable"></table>
      </div>
    </div>
    <div class="layui-form-item text-right pd-20">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
      <button class="layui-btn" id="addPurQualityTaskSubmit" type="button" style="display: none" lay-filter="addPurQualityTaskSubmit" lay-submit>提交</button>
    </div>
  </div>
</form>

<!-- 检测结果弹窗 -->
<script type="text/html" id="purQualityTaskCheckForm">
  <form lay-filter="purQualityTaskCheckForm" class="layui-form open-form purQualityTaskCheckForm">
    <div class="open-model">
      <div class="open-auto">
        <div class="layui-form-item">
          <div class="layui-form-item">
            <table class="layui-table" id="myPurQualityTaskDetailTable2" lay-filter="myPurQualityTaskDetailTable2"></table>
          </div>
          <div class="layui-form-item">
            <!-- 质检结果 -->
            <table class="layui-table" id="purQualityTaskCheckResultTable2" lay-filter="purQualityTaskCheckResultTable2"></table>
          </div>
        </div>
        <div class="layui-form-item text-right pd-20">
          <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
          <button class="layui-btn" id="submitPurQualityTaskCheck" type="button" style="display: none;" lay-filter="submitPurQualityTaskCheck" lay-submit>保存</button>
        </div>
      </div>
    </div>
  </form>
</script>
<!-- js部分 -->
<script>
  layui.use(["layer", "form", "table", "laydate", "admin", "laytpl", "upload", "config"], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var config = layui.config;
    var upload = layui.upload;
    var table = layui.table;
    var admin = layui.admin;
    var form = layui.form;
    let nowData = {};
    let where = [];
    if (typeof parentData !== "undefined") {
      nowData = { ...parentData };
    }
    const { data } = await admin.reqPro("enterprise/purchase/admin/myPurQualityTask/detail/" + nowData.data.id, {});
    console.log("data", data);

    table.render({
      elem: "#myPurQualityTaskFormTable",
      data: data ? [data] : [],
      cols: [
        [
          { field: "code", title: "质检任务编码" },
          { field: "sourceTypeName", title: "来源" },
          { field: "orderCode", title: "单据编号" },
          { field: "skuName", title: "取样物料信息" },
          { field: "submissionQuantity", title: "采购数" },
          { field: "qualityTestingCategoryName", title: "质检分类" },
          { field: "remark", title: "取样备注" },
          { field: "submissionQuantity", title: "取样数量" },
          { field: "okQuantity", title: "合格数量" },
          { field: "okRate", title: "合格率A" },
          { field: "okRate", title: "合格率B" },
          { field: "creatorName", title: "取样人" },
          { field: "createTime", title: "创建时间" }
        ]
      ]
    });
    table.render({
      elem: "#myPurQualityTaskDetailTable",
      data: data?.taskDetailList || [],
      cols: [
        [
          { type: "numbers", title: "序号" },

          { field: "code", title: "样品编码" },
          { title: "打印条码", templet: (d) => `<button type="button" class="layui-btn layui-btn-xs" lay-event="printBarCode">打印条码</button>` },
          { field: "status", title: "状态" },
          {
            field: "qualityTestingResult",
            title: "判定结果",
            templet: (d) => (String(d.qualityTestingResult) === "0" ? "合格" : String(d.qualityTestingResult) === "1" ? "不合格" : "待检")
          },
          { field: "dealWayName", title: "处置方式" },
          { field: "errorResult", title: "异常原因", templet: (d) => (d.errorResult ? d.errorResult : "无") },
          { field: "checkUserName", title: "检验员", templet: (d) => (d.checkUserName ? d.checkUserName : "待检") },
          { field: "checkTime", title: "检出时间", templet: (d) => (d.checkTime ? d.checkTime : "待检") },
          {
            title: "操作",
            templet: (d) =>
              d.checkTime
                ? `<button class="layui-btn layui-btn-xs" type="button" lay-event="detail">详情</button>`
                : `<button class="layui-btn layui-btn-xs" type="button" lay-event="check">检测</button>`
          }
        ]
      ]
    });
    table.on("tool(myPurQualityTaskDetailTable)", function (obj) {
      let data = obj.data;
      if (obj.event === "check") {
        openMyPurQualityTask(obj.event, data);
      } else if (obj.event === "detail") {
        openMyPurQualityTask(obj.event, data);
      }
    });
    function openMyPurQualityTask(event, data) {
      admin.formOpen({
        area: ["80%", "70%"],
        style: "font-size: 20px;",
        title: "录入质检结果",
        content: $("#purQualityTaskCheckForm").html(),
        success: function () {
          if (event == "check") {
            $("#submitPurQualityTaskCheck").show();
          }
          table.render({
            elem: "#myPurQualityTaskDetailTable2",
            data: data ? [data] : [],
            cols: [
              [
                { type: "numbers", title: "序号" },
                { field: "code", title: "样品编码" },
                { title: "打印条码", templet: (d) => `<button class="layui-btn layui-btn-xs" lay-event="printBarCode">打印条码</button>` },
                { field: "status", title: "状态" },
                {
                  field: "qualityTestingResult",
                  title: "判定结果",
                  templet: (d) => {
                    if (d.checkTime) {
                      return String(d.qualityTestingResult) === "0" ? "合格" : String(d.qualityTestingResult) === "1" ? "不合格" : "其他";
                    } else {
                      return admin.setTableSelect(
                        "qualityTestingResult",
                        [
                          { value: "0", label: "合格" },
                          { value: "1", label: "不合格" }
                        ],
                        event == "detail",
                        "qualityTestingResult"
                      )(d);
                    }
                  }
                },
                {
                  field: "dealWay",
                  title: "处置方式",
                  templet: admin.setTableSelect(
                    "dealWay",
                    [
                      { value: "2", label: "成品入库" },
                      { value: "0", label: "废品入库" },
                      { value: "1", label: "返修" }
                    ],
                    event == "detail",
                    "dealWay"
                  )
                },
                { field: "paperSlipPic", title: "上传照片", templet: admin.setTableUpload("paperSlipPic", event == "detail") },
                { field: "errorResult", title: "异常原因", templet: admin.setTableInput("errorResult", event == "detail") },
                { field: "checkUserName", title: "检验员", templet: (d) => (d.checkUserName ? d.checkUserName : "待检") },
                { field: "checkTime", title: "检出时间", templet: (d) => (d.checkTime ? d.checkTime : "待检") }
              ]
            ],
            done: function (res, curr, count) {
              //   $(".purQualityTaskCheckForm .layui-table-body,.purQualityTaskCheckForm .layui-table-box,.purQualityTaskCheckForm .layui-table-cell").css("overflow", "visible"); //显示高于表格

              admin.tableInputChange("myPurQualityTaskDetailTable2");
              admin.tableSelectChange("myPurQualityTaskDetailTable2", "dealWay");
              admin.tableSelectChange("myPurQualityTaskDetailTable2", "qualityTestingResult");
              upload.render({
                elem: ".upload-btn", // 绑定上传按钮
                url: config.upload_url + "uploadFile",
                accept: "file", // 可接受的文件类型
                headers: { Authorization: "Bearer " + config.getToken() },
                done: function (res, index, upload) {
                  // 上传成功的回调
                  if (res.code === 200) {
                    // 更新表格缓存中的数据
                    const button = $(this.item);
                    const index = button.data("index");
                    let tableData = table.cache["myPurQualityTaskDetailTable2"];
                    let rowIndex = tableData.findIndex((v) => v["LAY_TABLE_INDEX"] == index);
                    if (rowIndex > -1) {
                      tableData[rowIndex].paperSlipPic = res.data.url; // 假设接口返回的文件路径是 res.data.fileUrl
                    }
                    $(`#uploaded-${index}`).html(`<a href="${res.data.url}" target="_blank">查看附件</a>`);
                    console.log("文件上传成功:", res.data);
                  } else {
                    console.error("文件上传失败:", res.message);
                  }
                },
                error: function () {
                  // 上传失败的回调
                  console.error("上传失败");
                }
              });
            }
          });
          table.render({
            elem: "#purQualityTaskCheckResultTable2",
            data: data?.detailValues || [],
            cols: [
              [
                { type: "numbers", title: "序号" },
                { field: "qualityName", title: "参数项目名称" },
                { field: "no", title: "参数编码" },
                { field: "way", title: "检测方式" },
                { field: "utensil", title: "检测器具" },
                { field: "importance", title: "必检项" },
                { field: "standard", title: "质检标准" },
                { field: "trueValue", title: "实测值", templet: admin.setTableInput("trueValue", event == "detail") },
                {
                  field: "qualityValue",
                  title: "判定结果",
                  templet: admin.setTableSelect(
                    "qualityValue",
                    [
                      { value: "1", label: "合格" },
                      { value: "2", label: "不合格" }
                    ],
                    event == "detail",
                    "qualityValue"
                  )
                },
                { field: "remark", title: "备注", templet: admin.setTableInput("remark", event == "detail") }
              ]
            ],
            done: function (res, curr, count) {
              admin.tableInputChange("purQualityTaskCheckResultTable2");
              admin.tableSelectChange("purQualityTaskCheckResultTable2", "qualityValue");
            }
          });
          $(".purQualityTaskCheckForm").find(".layui-table-body,.layui-table-box,.layui-table-cell").css("overflow", "visible");
          form.on("submit(submitPurQualityTaskCheck)", function () {
            let myPurQualityTaskDetailTable2 = table.cache["myPurQualityTaskDetailTable2"];
            let purQualityTaskCheckResultTable2 = table.cache["purQualityTaskCheckResultTable2"];
            let fomrData = {};
            fomrData = myPurQualityTaskDetailTable2[0];
            fomrData.taskDetailId = myPurQualityTaskDetailTable2[0].id;
            fomrData.detailValues = purQualityTaskCheckResultTable2;
            console.log(fomrData);
              // return
            admin.req(
              "enterprise/purchase/admin/myPurQualityTask/detection",
              JSON.stringify(fomrData),
              async (res) => {
                if (res.code == 200) {
                  layer.msg("质检结果录入成功");
                  layer.close(parentData.zindex);
                  const { data } = await admin.reqPro("enterprise/purchase/admin/myPurQualityTask/detail/" + nowData.data.id, {});
                  table.reload("myPurQualityTaskDetailTable", {
                    data: data?.taskDetailList || []
                  });
                } else {
                  layer.msg("质检结果录入失败");
                }
              },
              "POST",
              true,
              "application/json; charset=utf-8"
            );
          });
        }
      });
    }
  });
</script>
<style>
  /* #myPurQualityTaskDetailTable2 .layui-table-cell {
    overflow: visible !important;
  } */
</style>
